package com.zx.map.controller;


import com.zx.map.service.ShareProfitDetailLogService;
import com.zx.map.service.ShareProfitLogService;
import com.zx.map.service.model.AgentInfoModel;
import com.zx.map.service.model.MerchantInfoModel;
import com.zx.map.service.model.ShareProfitDetailLogModel;
import com.zx.map.service.model.ShareProfitLogModel;
import com.zx.map.utils.SUConstants;
import com.zx.mobile.domain.ShareProfitDetailDomain;
import com.zx.platform.utils.DateUtils;
import com.zx.platform.utils.PmpUtils;
import com.zx.platform.utils.report.ReportUtil;
import com.zx.utils.WebUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;

/**
 * 平台端，查询分享收益
 */
@Controller
@RequestMapping("/manage/shareProfitDetailLog")
public class ShareProfitDetailLogController {
	/**
	 * log
	 */
	private static Logger log = Logger
			.getLogger(ShareProfitDetailLogController.class);

	@Autowired
	private ShareProfitDetailLogService shareProfitDetailLogService;


	@Autowired
	private ShareProfitLogService shareProfitLogService;

	/**
	 * 历史分享收益查询 edit by wenjw 2015.5.14
	 *
	 * @param domain
	 * @param model
	 * @param request
	 * @return
	 * @throws NoSuchAlgorithmException
	 * @throws UnsupportedEncodingException
	 */
	@RequestMapping("/shareProfitDetailList")
	public String shareProfitDetailList(ShareProfitDetailDomain domain,
			Model model, HttpServletRequest request) {

		try {// 初始化信息
			AgentInfoModel currentLoginAgentInfo= WebUtils.queryCurrentLoginAgentInfo(request);
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();
			MerchantInfoModel searchMerchantInfoModel=new MerchantInfoModel();
			initQueryData(domain, currentLoginAgentInfo, searchAgentInfoModel,searchMerchantInfoModel);

			Map map = shareProfitDetailLogService.getPageByDomain(currentLoginAgentInfo,searchAgentInfoModel,searchMerchantInfoModel,domain);
			setResultModelData(map,domain,model);
			return "/jsp/map/shareProfitDetail/shareProfitDetailList";
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	/**
	 * 下载详情
	 */
	@RequestMapping("/downLoadProfitDetailList")
	public String downLoadProfitDetailList(ShareProfitDetailDomain domain,
	                                    Model model, HttpServletRequest request, HttpServletResponse response) {
		try {// 初始化信息
			AgentInfoModel currentLoginAgentInfo= WebUtils.queryCurrentLoginAgentInfo(request);
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();
			MerchantInfoModel searchMerchantInfoModel=new MerchantInfoModel();
			initQueryData(domain, currentLoginAgentInfo, searchAgentInfoModel,searchMerchantInfoModel);
			domain.setPageSize(SUConstants.PAGE_NOT_PAGE_COUNT);
			Map map = shareProfitDetailLogService.getPageByDomain(currentLoginAgentInfo,searchAgentInfoModel,searchMerchantInfoModel,domain);
			downLoadProfitDetailList(map,response,"分享收益详情");
			return null;
		} catch (Exception e) {
			log.error("内部异常", e);
			model.addAttribute("errorMsg", "出错了");
			return "/jsp/platform/error";
		}
	}

	private void downLoadProfitDetailList(Map map, HttpServletResponse response,String fileName)throws Exception{
		List<ShareProfitDetailLogModel> reportList= (List<ShareProfitDetailLogModel>) map.get("list");

		Map<Integer, Object> formatAttr = new HashMap<Integer, Object>();
		formatAttr.put(1, ReportUtil.Date_Time2);
		formatAttr.put(5, ReportUtil.Decimal_Money_chn);

		String[] header = new String[]{"收益时间", "商户账号", "商户名称", "收益级别", "贡献收益", "代理账号","代理名称"};

		String[] feildName=new String[]{"createDate","merSysAccount","merchantName","spDetailTypeName",
				"spDetailAmt","agentSysAccount","agentName"};
		String sts = ReportUtil.exportReportXLS(header,reportList , null,
				fileName, formatAttr,feildName , response);
		String[] st = sts.split("#");
		ReportUtil.download(response, st[0], st[1]);
	}

	/**
	 * 我的分享收益日报表查询
	 *
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping("/querySpTrade")
	public String querySpTrade(ShareProfitDetailDomain domain, Model model, HttpServletRequest request,HttpServletResponse response) {
		try {
			//获取当前代理商信息
			AgentInfoModel currentAgentInfo= WebUtils.queryCurrentLoginAgentInfo(request);
			if(currentAgentInfo!=null){
				currentAgentInfo.setHasSelf(true);
				domain.setAgentSysAccount(currentAgentInfo.getSysAccount());
			}
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();
			MerchantInfoModel searchMerchantInfoModel=new MerchantInfoModel();
			initQueryData(domain,currentAgentInfo,searchAgentInfoModel,searchMerchantInfoModel);

			Map map = shareProfitDetailLogService.getMyShareProfitPageByDomain(currentAgentInfo,searchAgentInfoModel,searchMerchantInfoModel,domain);
			Double totalAmt = shareProfitDetailLogService.queryTotalSpDetailAmtByExample(currentAgentInfo,searchAgentInfoModel,searchMerchantInfoModel,domain);
			//查询自身总收益
			ShareProfitLogModel shareProfitLogModel =  shareProfitLogService
					.queryProfitByCustId(currentAgentInfo.getAgentId());
			model.addAttribute("myShareProfitLogModel",shareProfitLogModel); //总收益
			model.addAttribute("totalAmt", totalAmt.doubleValue());  //时间段内收益

			setResultModelData(map,domain,model);
			return "/jsp/map/shareProfitDetail/myShareProfitDetailList";
		} catch (Exception e) {
			model.addAttribute("errorMsg", "系统异常");
			log.error("系统异常", e);
			return "/jsp/platform/error";
		}
	}


	@RequestMapping("/downLoadMySpTrade")
	public String downLoadMySpTrade(ShareProfitDetailDomain domain, Model model, HttpServletRequest request,HttpServletResponse response) {
		try {
			//获取当前代理商信息
			AgentInfoModel currentAgentInfo= WebUtils.queryCurrentLoginAgentInfo(request);
			if(currentAgentInfo!=null){
				currentAgentInfo.setHasSelf(true);
				domain.setAgentSysAccount(currentAgentInfo.getSysAccount());
			}
			AgentInfoModel searchAgentInfoModel=new AgentInfoModel();
			MerchantInfoModel searchMerchantInfoModel=new MerchantInfoModel();
			initQueryData(domain,currentAgentInfo,searchAgentInfoModel,searchMerchantInfoModel);

			Map map = shareProfitDetailLogService.getPageByDomain(currentAgentInfo,searchAgentInfoModel,searchMerchantInfoModel,domain);
			downLoadProfitDetailList(map,response,"我的收益详情");
			return null;
		} catch (Exception e) {
			model.addAttribute("errorMsg", "系统异常");
			log.error("系统异常", e);
			return "/jsp/platform/error";
		}
	}

	private void initQueryData(ShareProfitDetailDomain domain, AgentInfoModel currentAgentInfo, AgentInfoModel searchAgentInfoModel, MerchantInfoModel searchMerchantInfoModel) {
		Integer pageNum = domain.getPageNum();
		Integer pageSize = domain.getPageSize();
		Integer pageCount = domain.getPageCount();
		if (null == pageNum) {
			pageNum = 1;
		}
		if (null == pageSize) {
			pageSize = 10;
		}

		domain.setPageSize(pageSize);
		domain.setPageNum(pageNum);
		if(SUConstants.PROFIT_LEVEL_WILL.equals(domain.getSpDetailType())){
			domain.setIsDirect(1);
		}
		//直属代理商查询
		if(domain.getIsDirect()>0&&currentAgentInfo!=null){
			domain.setParentAgentId(currentAgentInfo.getAgentId());
		}

		if (StringUtils.isBlank(domain.getBeginDate())) {
			domain.setBeginDate(PmpUtils.dateToString(
					DateUtils.getMonthFirstDateOf(new Date()), "yyyy-MM-dd"));
		}
		if (StringUtils.isBlank(domain.getEndDate())) {
			domain.setEndDate(PmpUtils.dateToString(new Date(),
					"yyyy-MM-dd"));
		}


		searchAgentInfoModel.setParentAgentId(domain.getParentAgentId());
		searchAgentInfoModel.setAgentName(domain.getAgentName());
		searchAgentInfoModel.setSysAccount(domain.getAgentSysAccount());
		//商户条件过滤
		searchMerchantInfoModel.setMerchantName(domain.getMerchantName());
		searchMerchantInfoModel.setSysAccount(domain.getMerSysAccount());
	}


	private void setResultModelData(Map map, ShareProfitDetailDomain domain, Model model) {
		int pageSize = domain.getPageSize();
		int pageNum = domain.getPageNum();
		List<ShareProfitDetailLogModel> shareProfitDetailList = (List<ShareProfitDetailLogModel>) map.get("list");
		int recordCount = Integer.valueOf(map.get("count").toString());
		// 页面信息
		if (pageSize * pageNum > recordCount + pageSize - 1) {
			pageNum = 1;
		}
		model.addAttribute("list", shareProfitDetailList);
		model.addAttribute("pageNum", pageNum);
		model.addAttribute("pageSize", pageSize);
		model.addAttribute("pageCount",
				PmpUtils.getPageCount(recordCount, pageSize));
		model.addAttribute("recordCount", recordCount);
		model.addAttribute("model", domain);
	}

}
